//
//  RegViewController.m
//  Kfangchan
//
//  Created by 朋飞 on 14-11-13.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "RegViewController.h"
#pragma mark 注册
#pragma mark
@interface RegViewController ()
@property (strong, nonatomic) IBOutlet UIButton *regBtn;
@property (strong, nonatomic) IBOutlet UIButton *getmsgBtn;
@property (strong, nonatomic) IBOutlet UIButton *agreementBtn;
@property (strong, nonatomic) IBOutlet UIButton *goAgreementBtn;

@property (strong, nonatomic) IBOutlet UITextField * nameTextField;
@property (strong, nonatomic) IBOutlet UITextField * phoneTextField;
@property (strong, nonatomic) IBOutlet UITextField * msgcodeTextField;
@property (strong, nonatomic) IBOutlet UITextField * psdTextField;
@property (strong, nonatomic) IBOutlet UITextField * requestcodeTextField;
@property (strong, nonatomic) IBOutlet UITextField * companycodeTextField;


@property (nonatomic) int seconds;
@property (nonatomic) int seleted_flag;





@end

@implementation RegViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 返回
    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"注册"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"nav_back.png"] Target:self Selector:@selector(back)];
    self.seleted_flag = 0;
    [self.getmsgBtn.layer setCornerRadius:5.0];
    [self.agreementBtn addTarget:self action:@selector(agreenment) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark 返回
#pragma mark
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark 注册
#pragma mark
-(IBAction)reg:(id)sender{
    BOOL verify  = [self verify];
    if(verify){
        //弱引用
        __weak RegViewController *weak_self = self;
        // 构建请求参数
        NSDictionary *param = @{
                                @"name":self.nameTextField.text,
                                @"mobile":self.phoneTextField.text,
                                @"passwd":self.psdTextField.text,
                                @"companyCode":self.companycodeTextField.text,
                                @"vericode":self.msgcodeTextField.text,
                                @"code":self.requestcodeTextField.text
                                };
        // 请求
        MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_REG completionHandler:^(id responseObject) {
            
            if(responseObject){
                id obj = [responseObject objectForKey:@"agent"];
                Agent *agent = [[Agent alloc] initWithDictionary:obj];
                agent.KFC_AGENT_MOBILE = [responseObject objectForKey:KFC_AGENT_MOBILE];
                agent.KFC_AGENT_PWD = [responseObject objectForKey:KFC_AGENT_PWD];
                agent.KFC_AGENT_UCID = [responseObject objectForKey:KFC_AGENT_UCID];
                [AppConfig setAgent:[agent dictionary]];
            }
            
            [weak_self dismissViewControllerAnimated:YES completion:nil];
            
        } errorHandler:^(NSError *error){
            showCustomAlertMessage(@"网路错误");
        }finishHandler:^(id responseObject) {
        }];
        
        [self.opHandlers addObject:operation];
        
    }
    
    
    
}
#pragma mark  获得短信验证码
#pragma mark
-(IBAction) getMsgcode{
    BOOL verify = [self verify:self.phoneTextField.text];
    if(verify){
        // 构建请求参数
        NSDictionary *param = @{
                                @"mobile":self.phoneTextField.text
                                };
        // 请求
        MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_VERIFY_PHONE completionHandler:^(id responseObject) {
            
            if(responseObject){
                [self startTime60];
            }
            
        } errorHandler:^(NSError *error){
            
            showCustomAlertMessage(@"网路错误");
            
        }finishHandler:^(id responseObject) {
            
        }];
        
        [self.opHandlers addObject:operation];
        
    }
    
    
}

#pragma mark  是否同意协议
#pragma mark
-(IBAction) agreenment{
    if(self.seleted_flag == 0){
        self.seleted_flag = 1;
        [self.agreementBtn setBackgroundImage: [UIImage imageNamed:@"agree_no_icon.png"] forState:UIControlStateNormal];
    }else{
        [self.agreementBtn setBackgroundImage: [UIImage imageNamed:@"agree_icon.png"] forState:UIControlStateNormal];
        self.seleted_flag = 0;
        
    }
    
}

#pragma mark  go 协议
#pragma mark
-(IBAction) go_agreenment:(id)sender{
    ArgreenViewController *argreen_vc = [[ArgreenViewController alloc] init];
    argreen_vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:argreen_vc animated:YES];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (BOOL) verify {
    NSString * name = self.nameTextField.text;
    NSString * phoneNum = self.phoneTextField.text;
    NSString * msgCode = self.msgcodeTextField.text;
    NSString * psd = self.psdTextField.text;
    //  NSString * requestCode = self.requestcodeTextField.text;
    UIAlertView * alert = nil;
    if (name.length<2) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的姓名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    if ( !validateMobile(phoneNum) ) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    if(msgCode.length!=4){
        alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入正确的短信验证码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    if(psd.length==0){
        alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入密码" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    if(self.seleted_flag ==1){
        
        alert = [[UIAlertView alloc]initWithTitle:nil message:@"请同意合作协议" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
        
    }
    
    //    if(password.length<6){
    //        alert = [[UIAlertView alloc]initWithTitle:nil message:@"用户名不少于6个字符" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    //        [alert show];
    //        return NO;
    //    }
    //
    
    
    
    return YES;
}
- (BOOL) verify: (NSString *) phone {
    
    UIAlertView * alert = nil;
    
    if ( !validateMobile(phone) ) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入正确的手机号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    return YES;
    
}


-(IBAction)isSelected:(id)sender{
    
}

#pragma mark -
#pragma mark 关闭键盘
- (IBAction)hideKeyboard {
    [self.nameTextField resignFirstResponder];
    [self.psdTextField resignFirstResponder];
    [self.phoneTextField resignFirstResponder];
    [self.msgcodeTextField resignFirstResponder];
    [self.requestcodeTextField resignFirstResponder];
    
}


-(void)startTime60{
    
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.getmsgBtn.layer setCornerRadius:5.0];
                self.getmsgBtn.backgroundColor =[UIColor colorWithHexString:@"66b97a"];
                [self.getmsgBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                self.getmsgBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.getmsgBtn.layer setCornerRadius:5.0];
                self.getmsgBtn.backgroundColor =[UIColor colorWithHexString:@"949494"];
                [self.getmsgBtn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                self.getmsgBtn.userInteractionEnabled = NO;
                
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    [self animateTextField:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self animateTextField:NO];
}

- (void)animateTextField:(BOOL)up {
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    float distance = (up ? -150 : 150);
    self.view.frame = CGRectAddY(self.view.frame, distance);
    //设置动画结束
    [UIView commitAnimations];
}

@end
